//--
app.factory('loginService', function($rootScope, $http, $location, $window, sessionService) {
	
	return {
		login:function(scope) {
			
			//-- Senha está criptografada no servidor. --
			var hash = CryptoJS.MD5(scope.usuario.senha).toString();
			scope.usuario.senha = hash.toString();
			
			$http
				.post(
					'service/login/acessar',
					scope.usuario,
					{
						headers : {
							'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
						}
					}).success(function(data) {
						if(data.status == true) {
							sessionService.set('usersessionid', data.object.session);
							sessionService.set('username', data.object.nome);
							sessionService.set('userprofile', data.object.perfil);
							$location.path('home');
						} else {
							showErrorMessage(data.message);
							scope.usuario.email = '';
							scope.usuario.senha = '';
						}
						
					}).error(function(data) {
						showErrorMessage('Problemas de comunica��o');
						console.log('error ->' + data);
					});
		},
		
		logout:function() {
			
			var $usersessionid = sessionService.get('usersessionid');
			
			$http
				.post(
					'service/login/sair',
					$usersessionid);
			
			sessionService.destroy('usersessionid');
			sessionService.destroy('username');
			sessionService.destroy('userprofile');
			sessionService.destroy('isLogged');
			$location.path('login');
			
		},
		
		isLogged:function() {
			
			var $usersessionid = sessionService.get('usersessionid');

			return $http
				.post(
					'service/login/validar',
					$usersessionid);
		}
	};
});